<?php

namespace Phone\Controller;

use Phone\Model\ExtensionModel;
use Phone\Model\MemberModel;
use Think\Controller;
use Common\Controller\PhoneController;

class GoodsController extends PhoneController {

    /**
     * 商品详情页
     * @param int $id 商品ID
     */
    public function index($id) {
        if (I('get.member_id')) {
            $arr = array('good_id' => $id, 'member_id' => I('get.member_id'));
            cookie('extension_share', json_encode($arr));
        }

        $ModelGoods = new \Phone\Model\GoodsModel();
        $ModelGoodsCat = new \Phone\Model\GoodsCatModel();
        $goods = $ModelGoods->where(Array('goods_id'=>$id))->find(); //获得商品详细信息
		if(empty($goods)){
		$this->redirect('/');
		}
		//$cat_ids = stringToarray($goods['cat_ids']);

        $this->total_goods = $ModelGoods->where(Array('cat_path_ids'=>array('like','%'.$goods['cat_ids'].'%')))->count();
		
        //类别名称
        $goods['cat_name'] =$ModelGoodsCat->get_all_cate($goods['cat_path_ids']); //$ModelGoodsCat->getAllPathName($goods['cat_ids']);
		
		$cat_id = str_replace(',', '', $goods['cat_ids']);
		$this->top_cat_id = $ModelGoodsCat->get_top_parent_id($cat_id);//获取顶级类别
        //大图展示
        $goods['picture_list'] = str_replace(",,", ",", $goods['picture_list']);
        $goods['arr_picture_list'] = explode(',', trim($goods['picture_list'],','));
        $goods['arr_picture_1'] = $goods['arr_picture_list'][0];
        
        $goods['price_cha'] = $goods['price_market'] - $goods['price'];
        //品牌
        $BrandObj = new \Phone\Model\GoodsBrandModel();
        $goods['brand_name'] = $BrandObj->get_name($goods['brand_id']);
        
        //筛选参数解析JSON
        $goods['spec_array'] = stripslashes($goods['spec_array']);
        $arr_par = json_decode($goods['spec_array'],true);
        
        //默认单件
        $item1 = $ModelGoods->get_item_first($id);
		$goods['store_num'] = M('goods_item')->where(Array('item_id'=>$item1['item_id']))->getField('store_num');
		
		
       
        //如果筛选参数不为空
        if(!empty($arr_par)) {
            foreach($arr_par as $k2 => $v2) {
                $arr_par[$k2]['sub'] = explode('|', $v2['val']);
                //过滤不存在选项
                foreach($arr_par[$k2]['sub'] as $k3 => $v3) {
                    $par = $v2['name'].':'.$v3;
                    if($ModelGoods->exist_item($id, $par) <= 0) {
                        unset($arr_par[$k2]['sub'][$k3]);
                    }
                }
            }
            $this->arr_par = $arr_par;
           //默认选择单件
            $arr_sel = array(); //默认单件选择数组
            $spec_array = $item1['spec_array'];
            $arr_spec_array = explode(',', $spec_array);
            foreach($arr_spec_array as $v) {
                $arr2 = explode(':', $v);
                //获得attr_id
                foreach($arr_par as $par) {
                    if($par['name'] == $arr2[0]) {
                       $arr_2_id = $par['id']; 
                    }
                }
                $arr_sel[$arr_2_id] = $arr2[1];
            }
            $this->arr_sel = $arr_sel;
            
        }
        $this->item_id = $item1['item_id'];
        $this->goods = $goods;
        
        //评价数量及星级
        $GoodsCommentObj = new \Phone\Model\GoodsCommentModel();
        $this->count_comment = $GoodsCommentObj->count_goods($id);//商品评价数
		/*
        $this->comment_star = $GoodsCommentObj->comment_star($id);//商品星级
        $this->count_star_12 = $GoodsCommentObj->count_star_12($id);//差评数
        $this->count_star_3 = $GoodsCommentObj->count_star_3($id);//中评数
        $this->count_star_45 = $GoodsCommentObj->count_star_45($id);//好评数
        $this->percent_star_3 = floor($this->count_star_3/$this->count_comment*100);
        $this->percent_star_12 = floor($this->count_star_12/$this->count_comment*100);
        $this->percent_star_45 = 100-$this->percent_star_3-$this->percent_star_12;
        */
		
        //商品评价
        $comment = $GoodsCommentObj->search($id,5);
		$this->p = I('p',0);//当前评价第几页
        $comment_list = $comment['list'];
        $comment_page = $comment['page'];
        $MemberObj = new \Phone\Model\MemberModel();
		
        foreach($comment_list as $k => $v) {
            $comment_list[$k]['headpic'] = $MemberObj->get_headpic($v['member_id']);
            $comment_list[$k]['member_name'] = $MemberObj->show_member_name($v['member_id']);
        }
		
        $this->comment_list = $comment_list;
        $comment_page = preg_replace('/p=(\d+)/', "p=$1#3", $comment_page);
        $this->comment_page = $comment_page;
       
        //商品自定义参数
        $par_arr = $ModelGoods->get_goods_attr($goods['model_id'], $id);
        $this->par_arr = $par_arr;
        
        //增加商品点击量
        $ModelGoods->add_hits($id);
        
        //显示商品浏览记录
        $this->history_list = $ModelGoods->history_show();
        //增加商品浏览记录
        $ModelGoods->history_add($id);
        
        //热销商品排行榜
        $top_parent_id = $ModelGoodsCat->get_top_parent_id($cat_id);
        $this->hot_list = $ModelGoods->get_hot_goods(8,$top_parent_id,$goods['goods_id']);
		
		/****商品收藏判断****/
		$FavObj = new \Phone\Model\MemberFavModel();
        $this->isfav = $FavObj->member_is_fav($id,$item1['item_id'],session('member_id'));
	   
		$this->color_array = get_goods_color_list($goods['spec_array']);//颜色列表
		$this->seo=array('seo_title'=>$goods['seo_title'],'seo_keywords'=>$goods['seo_keywords'],'seo_description'=>$goods['seo_description']);
		
		 $sql = "select sum(g.goods_num) as num  from ".C('DB_PREFIX')."order_goods g,".C('DB_PREFIX')."order o where g.goods_id=".$goods['goods_id']." and  o.order_id=g.order_id and o.status_pay = 3 and o.status <> 4 and o.status <> 5";
        $result = M('goods')->query($sql); //销售数量
		 $this->sell_num = $result[0]['num'];
			   $CartObj = new \Home\Model\CartModel();
        $cart_list = $CartObj->get_cart(); 
       
		$this->cart_count = count($cart_list);



		// extension
        $status = null;
        $member_id = session('member_id');

        if (!empty($member_id)) {
            $user = D('Member')->where(array('member_id' => $member_id))->find();
            if ($user['ex_level'] != '0') {
                $status = 1;
            }
        }
        $em = new ExtensionModel();
        $ex_profit= $em->get('ex_profit');
        $share = $goods['ex_share'] * ($ex_profit / 100);

        $this->assign('customer', C('CUSTOMER'));
        $this->assign('share', sprintf("%.2f", $share));
        $this->assign('status', $status);
        $this->display();
    }
    
    /**
     * 获得单件JSON数据
     * @param int $goods_id 商品ID
     * @param string $spec 规格参数
     */
    public function get_item($goods_id,$spec) {
        $ModelGoods = new \Phone\Model\GoodsModel();
        $row = $ModelGoods->get_item_spec($goods_id, $spec);

        if(!empty($row)) {
            $row['flag'] = 'success';
            $row['data'] = $row;
        } else {
            $row['flag'] = 'empty';
            $row['message'] = '不存在单件';
        }
        echo json_encode($row);
    }
    
    /**
     * 商品收藏
     * @param int $goods_id 商品ID
     */
    public function add_fav($goods_id,$item_id) {
        $data['status'] = 'error';
        $member_id = session('member_id');
        if (empty($member_id)) {
            $data['msg'] = 0;//请先登录或注册
        } else {
            $GoodsItemObj = M('goods_item');
            $price = $GoodsItemObj->where(array('goods_id'=>$goods_id,'item_id'=>$item_id))->getField('price');
            $FavObj = new \Phone\Model\MemberFavModel();
            $flag = $FavObj->add_fav($member_id, $goods_id,$item_id, $price);
            if($flag > 0) {
                $data['status'] = 'success';
                $data['msg'] = 1;//收藏成功
            } elseif ($flag == -2) {
				$data['status'] = 'success';
			    $flag = $FavObj->del_goods_fav($goods_id,$item_id,$member_id);
                $data['msg'] = -2;//你已收藏此商品
				
            } else {
                $data['msg'] = -3;//收藏失败
            }
        }
        $this->ajaxReturn($data);
    }
	
	
		    /**
     * 商品收藏
     * @param int $goods_id 商品ID
     */
    public function add_fav2($goods_id,$item_id) {
        $data['status'] = 'error';
        $member_id = session('member_id');
        if (empty($member_id)) {
            $data['msg'] = 0;//请先登录或注册
        } else {
            $GoodsItemObj = M('goods_item');
            $price = $GoodsItemObj->where(array('goods_id'=>$goods_id,'item_id'=>$item_id))->getField('price');
            $FavObj = new \Home\Model\MemberFavModel();
            $flag = $FavObj->add_fav($member_id, $goods_id,$item_id, $price);
            if($flag > 0) {
                $data['status'] = 'success';
                $data['msg'] = 1;//收藏成功
            } elseif ($flag == -2) {
				$data['status'] = 'success';
			    //$flag = $FavObj->del_goods_fav($goods_id,$item_id,$member_id);
                $data['msg'] = -2;//你已收藏此商品
				
            } else {
                $data['msg'] = -3;//收藏失败
            }
        }
        $this->ajaxReturn($data);
    }
    
    

}
